package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.repository.qimen.DeliveryOrderTaskDao;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.DeliveryOrderRequest;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.qmentity.response.deliveryorder.DeliveryorderResponse;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.rest.qimen.util.validator.ValidatorUtil;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.utils.rule.TMSTransportRule;

/**
 * 发货单业务处理类
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2015-5-8      CC            1.0           Create
 */
@Component
public class DeliveryOrderReceiveService {
    private static final Logger logger = LoggerFactory.getLogger(DeliveryOrderReceiveService.class);
    
	@Autowired
	private DeliveryOrderTaskDao deliveryOrderTaskDao;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public ResponseParams execute(RequestParams params) throws PaiUException {
		ResponseParams response = new ResponseParams();
		DeliveryorderResponse deliveryorderResponse = new DeliveryorderResponse();
		String stringXml = params.getRequestXml() ;
		
		DeliveryOrderRequest deliveryOrderRequest = JAXB.unmarshal(new StringReader(stringXml), DeliveryOrderRequest.class);
		// 报文校验
        String reqValidatorMsg = ValidatorUtil.qmXmlValidator(deliveryOrderRequest);
        if (!ValidatorUtil.SUCCESS_CODE.equals(reqValidatorMsg)) {
            response.setResponseXml(reqValidatorMsg.toString());
            return response;
        }
        
		//-------原来的校验方式 start
		Map<String,String> checkInfo = ediGoodsSkuService.toCheckItemId(deliveryOrderRequest) ;
		if(checkInfo.get("msg").equals("success")){
			DeliveryOrderTask task = new DeliveryOrderTask();
			task.setContent(params.getRequestXml());
			task.setOrderNo(TMSTransportRule.generateOrderNo());
			task.setDealCount(0);
			task.setDealStatus("0");
			task.setWarehouseCode(deliveryOrderRequest.getDeliveryOrder().getWarehouseCode());
			task.setCustomerCode(deliveryOrderRequest.getDeliveryOrderItems().get(0).getOwnerCode());
			//取消单处理 根据客户订单号 20161025
			task.setCustomerOrderNo(deliveryOrderRequest.getDeliveryOrder().getDeliveryOrderCode());
			task.setCrTime(new Date());
			deliveryOrderTaskDao.save(task);
			
			deliveryorderResponse.setFlag(ResponseFlagType.SUCCESS.getType());
			deliveryorderResponse.setCode(QMErrorCode.SUCCESS.getCode());
			deliveryorderResponse.setMessage(QMErrorCode.SUCCESS.getMessage());
			deliveryorderResponse.setCreateTime(new Date());
			deliveryorderResponse.setDeliveryOrderId(task.getOrderNo());
		}else{
			logger.info("出库单报文校验-->商品编码错误："+checkInfo.get("message"));
			deliveryorderResponse.setFlag(ResponseFlagType.FAILURE.getType());
			deliveryorderResponse.setCode(QMErrorCode.FAILURE.getCode());
			deliveryorderResponse.setMessage("失败："+checkInfo.get("message"));
			deliveryorderResponse.setCreateTime(null);
			deliveryorderResponse.setDeliveryOrderId("");
		}
		//-------原来的校验方式 end
		
		// JSR 303 校验 修改时请先查看 ediGoodsSkuService.toCheckItemId
		/*DeliveryOrderTask task = new DeliveryOrderTask();
        task.setContent(params.getRequestXml());
        task.setOrderNo(TMSTransportRule.generateOrderNo());
        task.setDealCount(0);
        task.setDealStatus("0");
        deliveryOrderTaskDao.save(task);
        
        deliveryorderResponse.setFlag(ResponseFlagType.SUCCESS.getType());
        deliveryorderResponse.setCode(QMErrorCode.SUCCESS.getCode());
        deliveryorderResponse.setMessage(QMErrorCode.SUCCESS.getMessage());
        deliveryorderResponse.setCreateTime(new Date());
        deliveryorderResponse.setDeliveryOrderId(task.getOrderNo());*/
		// JSR 303 校验
        
		StringWriter sw = new StringWriter();
		JAXB.marshal(deliveryorderResponse, sw);
		response.setResponseXml(sw.toString());
		return response;
	}
	
}
